<template>
    <div id="Login">
     
        <el-form ref="dataForm" :model="loginForm" status-icon :rules="rules" class="loginForm">
            <el-form-item prop="email">
                <el-input v-model="loginForm.email" type="email" placeholder="邮箱" />
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="密码" />
            </el-form-item>
            <el-form-item prop="repassword">
                <el-input v-model="loginForm.repassword" type="password" placeholder="确认密码" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loginBtn(dataForm)">登录</el-button>
                <el-button type="info" @click="this.$router.push('/task03/register')">注册</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup>
import { login } from '@/api/user'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()


const loginForm = reactive({
    email: '553931196@qq.com',
    password: '123456789',
    repassword: '123456789'
})

const dataForm = ref()

const checkRepass = (rule, value, callback) => {
    if (value != loginForm.password) {
        callback("两次密码输入不一致")
    } else {
        callback()
    }
}

const rules = reactive({
    email: [{
        required: true,
        message: "请输入邮箱",
        trigger: 'blur'
    }],
    password: [{
        required: true,
        message: "请输入密码",
        trigger: 'blur'
    }],
    repassword: [{
        required: true,
        message: "请再次输入密码",
        trigger: 'blur'
    },
    {
        validator: checkRepass,
        trigger: 'blur'
    }]
})

const loginBtn = (dataForm) => {
    dataForm.validate(valid => {
        if (valid) {
            login(loginForm).then(res => {
                //保存登录状态信息
                userStore.$patch({
                    islogin: true,
                    user: res.data.userinfo
                })
                localStorage.setItem('token', userStore.user.token)
                ElMessage({
                    message: '登录成功',
                    type: 'success',
                })
                router.push({
                    path: '/task03/user'
                })
            })
        }
    })
}


</script>
<style scoped>
#Login {
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.loginForm {
    width: 400px;
}

.login-tools {
    display: flex;
}

button {
    width: 200px;
    margin: 5px 0px !important;
    color: white;
   
}
</style>